const app = getApp()

const { extend, Field, Switch, Stepper, Toast, Actionsheet } = require('../../zanui/index')
import { obj2Form } from '../../utils/util.js'

Page(extend({}, Field, Switch, Stepper, Toast, Actionsheet, {

  /**
   * 页面的初始数据
   */
  data: {
    isHotelNavigation: 'false',
    isShowAddHotelRoom: false,
    submitDisabled: false,
    uploadDisabled: false,
    showMoreImgOption: false,
    //canNavitoHotelRoom: true,
    moreImgOption: [{
      name: '删除该图片'
    }],
    id: '',
    selectImg: null,
    hotelImages: [],//酒店图片
    hotelLevels: [],//酒店星级
    payTypes: [],//支付方式选择
    hotelTypes: [],//酒店类型
    hotelFacilitys: [],//酒店设备  
    hotelServices: [],//酒店服务类型 
    hotelName: '',
    hotelAddress: '',
    longitude: 0,
    latitude: 0,
    hotelTel: '',
    hotelLevel: 0,
    referencePrice: 0,
    storeOpeningDate: '1960-01-01',
    latelyDecorationDate: '1960-01-01',
    decorationType: 0,
    roomsNum: 0,
    numberOfFloorLevels: 0,
    hotelBrand: '',
    hotelType: 0,
    supportPayType: '',
    hotelPrincipalTel: '',
    hotelIntro: '',
    hotelFacility: '',
    hotelService: '',
    createBy: '',
    hotelImage: '',
    areaId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '酒店基本信息'
    });

    if (options.id != '' && options != undefined && options.id != null) {
      this.setData({
        id: options.id,
        isHotelNavigation: options.isHotelNavigation,
        isShowAddHotelRoom: true
      });

      this.getHotelDataById()
    } else {
      this.getHotelLevel()
      this.getHotelFacility()
      this.getPayType()
      this.getHotelService()
      this.getHotelType()
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 酒店星级选择事件
   */
  hotelRadioChange: function (event) {
    this.setData({
      hotelLevel: event.detail.value
    });
  },

  /**
   * 装修类型选择事件
   */
  decorationTypeChange: function (event) {
    this.setData({
      decorationType: event.detail.value
    });
  },

  /**
   * 酒店类型选择事件
   */
  hotelTypeRadioChange: function (event) {
    this.setData({
      hotelType: event.detail.value
    });
  },

  /**
   * 支付方式选择事件
   */
  payTypeCheckboxChange: function (event) {
    this.setData({
      supportPayType: event.detail.value.toString().replace(/,/g, ';')
    });
  },

  /**
   * 酒店设施选择事件
   */
  facilityCheckboxChange: function (event) {
    this.setData({
      hotelFacility: event.detail.value.toString().replace(/,/g, ';')
    });
  },

  /**
   * 酒店服务选择事件
   */
  serviceCheckboxChange: function (event) {
    this.setData({
      hotelService: event.detail.value.toString().replace(/,/g, ';')
    });
  },

  /**
   * 日期、时间选择事件绑定
   */
  bindDatePickerChange: function (e) {
    this.setData({
      [`${e.currentTarget.id}`]: e.detail.value
    });
  },

  /**
   * 定位
   */
  bindSelectMap: function () {
    const _self = this
    wx.chooseLocation({
      success: (data) => {
        _self.setData({
          latitude: data.latitude,
          longitude: data.longitude,
          hotelAddress: data.address
        });

        //根据经纬度获取别的信息
        wx.request({
          url: 'https://api.map.baidu.com/geocoder/v2/?ak=PgtdDGnL4iGj083t7b7d0fAO&callback=renderReverse&output=json&pois=1&location=' + _self.data.storeLatitude + ',' + _self.data.storeLongitude,
          success: (res) => {
            const currData = JSON.parse(res.data.substring(res.data.indexOf("(") + 1, res.data.lastIndexOf(")")));
            _self.setData({
              storeBelongProvince: currData.result.addressComponent.province,
              storeBelongRegion: currData.result.addressComponent.district
            });

          },
          fail: (err) => {
            this.showZanToast('加载省份，行政区失败！');
          }
        })
      }
    })
  },

  /**
   * 提交数据
   */
  formSubmit: function (event) {
    //追加单选钮数据
    const formData = event.detail.value;
    formData.decorationType = this.data.decorationType;
    formData.hotelType = this.data.hotelType;
    formData.hotelLevel = this.data.hotelLevel;
    formData.supportPayType = this.data.supportPayType;
    formData.hotelFacility = this.data.hotelFacility;
    formData.hotelService = this.data.hotelService;
    formData.areaId = app.globalData.areaInfo.id;
    if (this.data.isHotelNavigation == 'true') {
      formData.id = this.data.id;
      formData.updateBy = app.globalData.userInfo.openid;
    } else {
      formData.createBy = app.globalData.userInfo.openid;
      formData.updateBy = app.globalData.userInfo.openid;
    }
    
    let imagePath = '';
    this.data.hotelImages.forEach((item, index) => {
      imagePath += item.downloadPath + ";";
    });
    
    formData.hotelImages = imagePath.substring(0, imagePath.length - 1)

    for (let key in formData) {
      if (key == 'hotelImages') {
        continue
      } else {
        if (formData[key] === '') {
          this.showZanToast('数据不能为空')
          return
        }
      }
    }
    wx.showLoading({
      title: '上传中',
    });
    const _self = this
    let requestUrl = ''
    let method = ''
    if (_self.data.id != '' && _self.data.id != null && _self.data.id != undefined) {
    //if (_self.data.isHotelNavigation == 'true') {
      requestUrl = 'https://qdndc.ideatower.cn/v1/hotel/' + _self.data.id
      method = 'PUT'
    } else {
      requestUrl = 'https://qdndc.ideatower.cn/v1/hotel'
      method = 'POST'
    }
    wx.request({
      url: requestUrl,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: obj2Form(formData),
      method: method,
      success: function (res) {
        console.log(res.data)
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000
        })
        if (res.data.code == '000000') {
          _self.showZanToast('更新成功')
          wx.navigateBack({
            
          })
        }
        if (res.statusCode != 200) {
          _self.showZanToast('请求接口失败')
          return
        }
        _self.setData({
          id: res.data.data.id
        });
      },
      fail: function () {
        _self.showZanToast('网络错误')
      },
      complete: function () {
        _self.setData({
          submitDisabled: false
        })
        wx.hideLoading()
      }
    })
  },

  /**
   * 导航房间信息录入
   */
  navitoHotelRoomPage: function () {
    if (this.data.id != '' && this.data.id != undefined) {
      wx.navigateTo({
        url: '../hotelRoom/hotelRoom?id=' + this.data.id,
      })
    } else {
      this.showZanToast('获取房间ID失败')
    }
  },

  /**
   * 导航到房间列表
   */
  navitoHotelRoomListPage: function () {
    const belongHotelID = this.data.id;
    if (belongHotelID != '' && belongHotelID != null && belongHotelID != undefined) {
      wx.navigateTo({
        url: '../hotelRoomList/hotelRoomList?id=' + this.data.id,
      })
    }
  },

  getHotelLevel: function () {
    //酒店星级
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/hotelLevel',
      success: (res) => {
        if (res.data.data.length > 0) {
          this.setData({
            hotelLevels: res.data.data
          });
          //绑定数据
          if (this.data.hotelLevel != undefined && this.data.isHotelNavigation == 'true') {
            this.data.hotelLevels.forEach((item, index) => {
              if (this.data.hotelLevel == item.id) {
                item.checked = true
              } else {
                item.checked = false
              }
            });

            this.setData({
              hotelLevels: this.data.hotelLevels
            })
          }
        } else {
          this.showZanToast('暂无酒店星级信息');
        }
      },
      fail: (err) => {
        this.showZanToast('获取酒店星级失败');
      }
    })
  },
  getHotelFacility: function () {
    //酒店设备
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/hotelFacility',
      success: (res) => {
        if (res.data.data.length > 0) {
          this.setData({
            hotelFacilitys: res.data.data
          })
          if (this.data.isHotelNavigation == 'true') {
            if (this.data.hotelFacility != '' && this.data.hotelFacility != null && this.data.hotelFacility != undefined) {
              let temHotelFacility = this.data.hotelFacility.split(';')
              this.data.hotelFacilitys.forEach((item, index) => {
                const findIndex = temHotelFacility.findIndex(o => o == item.id)
                if (findIndex > -1) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              });
              this.setData({
                hotelFacilitys: this.data.hotelFacilitys
              })
            }
          }
        } else {
          this.showZanToast('暂无酒店设备信息');
        }
      },
      fail: (err) => {
        this.showZanToast('获取酒店设备失败');
      }
    })
  },

  getPayType: function () {
    //支付方式
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/payType',
      success: (res) => {
        if (res.data.data.length > 0) {
          this.setData({
            payTypes: res.data.data
          });
          
          if (this.data.isHotelNavigation == 'true') {
            if (this.data.supportPayType != '' && this.data.supportPayType != null && this.data.supportPayType != undefined) {
              let temPayType = this.data.supportPayType.split(';')
              this.data.payTypes.forEach((item, index) => {
                const findIndex = temPayType.findIndex(o => o == item.id)
                if (findIndex > -1) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              });
              this.setData({
                payTypes: this.data.payTypes
              })
            }
          }
        } else {
          this.showZanToast('暂无支付方式信息');
        }
      },
      fail: (err) => {
        this.showZanToast('获取支付方式失败');
      }
    });
  },

  getHotelService: function () {
    //服务类型
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/hotelService',
      success: (res) => {
        if (res.data.data.length > 0) {
          this.setData({
            hotelServices: res.data.data
          });

          if (this.data.isHotelNavigation == 'true') {
            if (this.data.hotelService != '' && this.data.hotelService != null && this.data.hotelService != undefined) {
              let temHotelService = this.data.hotelService.split(';')
              this.data.hotelServices.forEach((item, index) => {
                const findIndex = temHotelService.findIndex(o => o == item.id)
                if (findIndex > -1) {
                  item.checked = true
                } else {
                  item.checked = false
                }
              });
              this.setData({
                hotelServices: this.data.hotelServices
              })
            }
          }
        } else {
          this.showZanToast('暂无服务方式信息');
        }
      },
      fail: (err) => {
        this.showZanToast('获取服务方式失败');
      }
    });
  },

  getHotelType: function () {
    //酒店类型
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/hotelType',
      success: (res) => {
        if (res.data.data.length > 0) {
          this.setData({
            hotelTypes: res.data.data
          });

          if (this.data.hotelType != undefined && this.data.isHotelNavigation == 'true') {
            this.data.hotelTypes.forEach((item, index) => {
              if (this.data.hotelType == item.id) {
                item.checked = true
              } else {
                item.checked = false
              }
            });

            this.setData({
              hotelTypes: this.data.hotelTypes
            })
          }
        } else {
          this.showZanToast('暂无酒店类型信息');
        }
      },
      fail: (err) => {
        this.showZanToast('获取酒店类型失败');
      }
    })
  },

  /**
   * 根据ID获取酒店数据
   */
  getHotelDataById: function () {
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/hotel?id=' + this.data.id,
      success: (res) => {
        if (res.data.data.length > 0) {
          const responseData = res.data.data[0];
          this.setData({
            hotelName: responseData.hotelName,
            hotelAddress: responseData.hotelAddress,
            longitude: responseData.longitude,
            latitude: responseData.latitude,
            hotelTel: responseData.hotelTel,
            hotelLevel: responseData.hotelLevel,
            referencePrice: responseData.referencePrice,
            storeOpeningDate: responseData.storeOpeningDate,
            latelyDecorationDate: responseData.latelyDecorationDate,
            decorationType: responseData.decorationType,
            roomsNum: responseData.roomsNum,
            numberOfFloorLevels: responseData.numberOfFloorLevels,
            hotelBrand: responseData.hotelBrand,
            hotelType: responseData.hotelType,
            supportPayType: responseData.supportPayType,
            hotelPrincipalTel: responseData.hotelPrincipalTel,
            hotelIntro: responseData.hotelIntro,
            hotelFacility: responseData.hotelFacility,
            hotelService: responseData.hotelService,
            createBy: responseData.createBy,
            hotelImage: responseData.hotelImages,
            areaId: responseData.areaId,
          })
          if (this.data.hotelImage) {
            const tmp = []
            this.data.hotelImage.split(';').forEach((item, index) => {
              tmp.push({
                id: new Date().getTime() + '-' + index,
                src: item,
                downloadPath: item,
                uploadStatus: 1
              })
            })
            this.setData({
              hotelImages: tmp
            })
          }

          this.getHotelLevel()
          this.getHotelFacility()
          this.getPayType()
          this.getHotelService()
          this.getHotelType()
        } else {
          this.showZanToast('获取酒店数据失败');
        }
      },
      fail: (err) => {

      }
    })
  },
  
  /**
   * 选择图片
   * @param {*} e 
   */
  selectImgs: function(e) {
    const _self = this
    wx.chooseImage({
      count: 12,
      sizeType: ['original'],
      sourceType: ['album'],
      success: function (res) {
        let tmp = _self.data.hotelImages
        res.tempFilePaths.forEach((path, index) => {
          tmp.push({
            id: new Date().getTime() + '-' + index,
            src: path,
            uploadStatus: 0
          })
        })
        if (tmp.length > 12) {
          tmp = tmp.slice(0, 12)
        }
        _self.setData({
          hotelImages: tmp
        })
      }
    })
  },
  /**
   * 上传图片
   */
  uploadImg: function() {
    this.setData({
      uploadDisabled: true
    })
    wx.showLoading({
      title: '上传图片中',
    })

    //函数数组，每个函数的返回值是一个promise对象
    let promiseFuncArr = []
    const _self = this
    this.data.hotelImages.forEach(item => {
      if (item.uploadStatus != 1) {
        let promiseTemp = function () {
          return new Promise((resolve, reject) => {
            wx.uploadFile({
              url: 'https://qdndcupload.ideatower.cn/apiAttachment/uploadAttachment?bucketName=qdndc',
              filePath: item.src,
              name: 'file',
              success: function (res) {
                var data = JSON.parse(res.data)
                if (data.code == 0) {
                  item.downloadPath = data.data[0].downloadPath
                }
                resolve(item)
              },
              fail: function () {
                reject(error)
              }
            })
          })
        }
        promiseFuncArr.push(promiseTemp)
      }
    })
    _self.sequenceTasks(promiseFuncArr).then((result) => {
      //对返回的result数组进行处理
      console.log(result)
      if (promiseFuncArr.length == 0) {
        wx.hideLoading()
        this.showZanToast('请至少选择一张新的图片')
        return
      }
      result.forEach(item => {
        if (item.downloadPath) {
          item.uploadStatus = 1
        } else {
          item.uploadStatus = -1
        }
      })
      _self.data.hotelImages.forEach(item => {
        const findObj = result.find(o => o.id == item.id)
        if (findObj) {
          item = Object.assign({}, item, findObj)
        }
      })
      _self.setData({
        hotelImages: _self.data.hotelImages,
        uploadDisabled: false
      })
      
      wx.hideLoading()
    })
  }, 
  /**
   * 长按删除操作
   */
  deleteImgLongTab(e) {
    let index = e.currentTarget.id.substring(3)
    const img = this.data.hotelImages[parseInt(index)]
    if (img.uploadStatus == -1) {
      this.setData({
        moreImgOption: [{
          name: '删除该图片'
        }, {
          name: '重新上传'
        }]
      })
    } else {
      this.setData({
        moreImgOption: [{
          name: '删除该图片'
        }]
      })
    }

    this.setData({
      selectImg: img,
      showMoreImgOption: true
    })
  },
  handleZanActionsheetClick: function({ componentId, index }) {
    if (this.data.selectImg) {
      const t1 = this.data.hotelImages
      if (index == 0) {
        // 删除
        const findIndex1 = t1.findIndex(o => o.id == this.data.selectImg.id)
        if (findIndex1 > -1) {
          t1.splice(findIndex1, 1)
          this.setData({
            hotelImages: t1
          })
        }
      } else {
        // 重新上传
        wx.showLoading({
          title: '上传图片中',
        })
        const obj = t1.find(o => o.id == this.data.selectImg.id)
        if (obj) {
          const _self = this
          wx.uploadFile({
            url: 'https://qdndcupload.ideatower.cn/apiAttachment/uploadAttachment?bucketName=qdndc',
            filePath: obj.src,
            name: 'file',
            success: function (res) {
              var data = JSON.parse(res.data)
              if (data.code == 0) {
                obj.downloadPath = data.data[0].downloadPath
              }
            },
            fail: function () {
            },
            complete: function () {
              t1.forEach(item => {
                if (item.id == obj.id) {
                  if (obj.downloadPath) {
                    item.uploadStatus = 1
                    item.downloadPath = obj.downloadPath
                  } else {
                    item.uploadStatus = -1
                  }

                }
              })
              _self.setData({
                hotelImages: t1,
              })
              wx.hideLoading()
            }
          })
        }
      }
      this.setData({
        showMoreImgOption: false
      })
    }
  },
  handleZanActionsheetCancel: function() {
    this.setData({
      showMoreImgOption: false
    })
  },
  //顺序处理函数
  sequenceTasks: function(tasks) {
    //记录返回值
    function recordValue(results, value) {
      results.push(value)
      return results
    }
    let pushValue = recordValue.bind(null, [])
    return tasks.reduce(function (promise, task) {
      return promise.then(task).then(pushValue)
    }, Promise.resolve())
  },
}))